import { NavigationActions } from 'react-navigation'
import store from '@store'

let _navigator
let _routers
let _navigation

/**
 * 设置顶层路由导航
 * @param navigatorRef
 */
function setTopLevelNavigator (navigatorRef) {
  _navigator = navigatorRef
}

/**
 * 设置当前路由栈和导航对象
 * @param routers
 * @param navigation
 */
function setRouters (routers, navigation) {
  _routers = routers
  _navigation = navigation
}

function getNavigator () {
  return _navigator
}

function getNavigation () {
  if (!_navigator) return
  return _navigator._navigation
}

/**
 * 跳转到指定页面
 * @param routeName
 * @param params
 */
function navigate (routeName, params) {
  if (!_navigator) return
  _navigator.dispatch(
    NavigationActions.navigate({
      type: NavigationActions.NAVIGATE,
      routeName,
      params
    })
  )
}

/**
 * 跳转到指定页面
 * @param routeName
 * @param navigateParams
 * @param firstUserInfoParams
 */
function jumpLogin ({ firstUserInfoParams } = {}) {
  const { userinfo } = store.getState()
  const { role } = userinfo

  if (role === 'C') { // C端
    const { userId, C: { userId: userIdC } } = userinfo
    if (!userId) {
      navigate('OneLogin')
      return true
    } else if (!userIdC) {
      navigate('CFirstUserInfo', firstUserInfoParams)
      return true
    }
  } else { // B端
    const { userId, B: { userId: userIdB } } = userinfo
    if (!userId) {
      navigate('OneLogin')
      return true
    } else if (!userIdB) {
      navigate('BFirstUserInfo', firstUserInfoParams)
      return true
    }
  }
  return false
}

/**
 * 跳转到指定页面
 * @param routeName
 * @param navigateParams
 * @param firstUserInfoParams
 */
function navigateWithLogin ({ routeName, navigateParams, firstUserInfoParams } = {}) {
  if (!jumpLogin({ firstUserInfoParams })) {
    navigate(routeName, navigateParams)
  }
}

/**
 * 返回到顶层
 */
function popToTop () {
  if (!_navigator) return
  _navigator.dispatch(NavigationActions.popToTop())
}

/**
 * 返回第n个页面
 * @param n
 */
function popToN (n) {
  if (n <= 0) {
    return
  }
  const len = _routers.length
  if (len < n || n === len - 1) {
    this.popToTop()
    return
  }
  if (!_navigation) return
  _navigation.goBack(_routers[len - n].key)
}

/**
 * 返回
 */
function goBack () {
  if (!_navigator) return
  _navigator.dispatch(NavigationActions.back({ type: NavigationActions.BACK }))
}

/**
 * 返回到任意页面
 * @param routeName
 */
function popToRouter (routeName) {
  if (!routeName) {
    this.goBack()
    return
  }
  const len = _routers.length
  for (let i = 0; i < len - 1; i++) {
    const route = _routers[i]
    if (routeName === route.routeName && i !== len - 1) {
      if (!_navigation) return
      _navigation.goBack(_routers[i + 1].key)
      return
    }
  }
}

export default {
  setTopLevelNavigator,
  setRouters,
  getNavigator,
  getNavigation,
  navigate,
  popToRouter,
  goBack,
  popToTop,
  jumpLogin,
  navigateWithLogin
}
